<?php
namespace App\Models\Trade\Supply;

use App\Models\Model;

class SupplyRefreshModel extends Model
{

    const TABLENAME = 'tw_trade_supply_refresh';

    /**
     * 获取一条数据（今天）
     *
     * @param int $userId
     * @param int $supplyId
     * @return \Illuminate\Support\Collection
     */
    public static function findItemByToday($userId, $supplyId)
    {
        $where[] = ['user_id', $userId];
        $where[] = ['supply_id', $supplyId];
        $where[] = ['created', '>', strtotime('today')];
    
        return self::dbTable()->where($where)->get();
    }
    
    /**
     * 添加一条数据（今天）
     *
     * @param int $userId
     * @param int $supplyId
     * @return false | 1 | 0 | id
     */
    public static function addItemByToday($userId, $supplyId)
    {
        if (! $userId || ! $supplyId) {
            return false;
        }
        $data['updated'] = time();
    
        $item = self::findItemByToday($userId, $supplyId)->shift();
        if ($item) {
            return self::dbTable()->where('id', $item['id'])->increment('amount', 1, $data);
        } else {
            $data['created'] = $data['updated'];
            $data['user_id'] = $userId;
            $data['supply_id'] = $supplyId;
            $data['amount'] = 1;
    
            return self::dbTable()->insertGetId($data);
        }
    }
}
